package com.kakaxi.mybilibili.module.home.live.view;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import com.andexert.library.RippleView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.kakaxi.mybilibili.R;
import com.kakaxi.mybilibili.adapter.LiveCategoryRoomsContentRecyAdapter;
import com.kakaxi.mybilibili.adapter.LiveCategoryRoomsTagRecyAdapter;
import com.kakaxi.mybilibili.adapter.tag.LiveCategoryRoomsTagFlowAdapter;
import com.kakaxi.mybilibili.base.NavigationActivity;
import com.kakaxi.mybilibili.bean.LiveItemBean;
import com.kakaxi.mybilibili.module.home.MainActivity;
import com.kakaxi.mybilibili.module.home.live.presenter.ILiveCategoryRoomsPresenter;
import com.kakaxi.mybilibili.module.home.live.presenter.LiveCategoryRoomsPresenter;
import com.kakaxi.mybilibili.utils.NetworkCheckUtil;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 分区直播间活动类
 * Created by kakaxi on 16/11/15.
 */

public class LiveCategoryRoomsActivity extends NavigationActivity implements
        ILiveCategoryRoomsView {

    /** 标签水平列表 **/
    @BindView(R.id.recv_live_category_rooms_tag_list)
    RecyclerView mTagRecyView;

    /** 直播间列表 **/
    @BindView(R.id.recv_live_category_rooms_list)
    RecyclerView mRoomsRecvView;

    /** 刷新控件 **/
    @BindView(R.id.srl_live_category_rooms_refresh)
    SwipeRefreshLayout mRefreshSRLayout;

    /** 第二层标签线性布局 **/
    @BindView(R.id.llayout_live_category_rooms_content2)
    LinearLayout mTagContentLayout2;

    /** 标签流式布局 **/
    @BindView(R.id.tflayout_live_category_rooms_tag_list)
    TagFlowLayout mTagTFLayout;

    /** 标签下拉按钮 **/
    @BindView(R.id.ibtn_live_category_rooms_tag_open)
    ImageButton mTagOpenImgBtn;

    /** 排序按钮组 **/
    @BindView(R.id.group_live_category_rooms_sort)
    RadioGroup mSortGroup;

    /** 分区id传递参数 **/
    public static final String EXTRA_AREA_CATEGORY_ID = "areaCategoryId";
    /** 标题传递参数 **/
    public static final String EXTRA_TITLE = "title";

    /** 控制层 **/
    private ILiveCategoryRoomsPresenter mPresenter;

    /** 水平列表适配器 **/
    private LiveCategoryRoomsTagRecyAdapter mTagRecyAdapter;
    /** 直播间列表适配器 **/
    private LiveCategoryRoomsContentRecyAdapter mRoomsRecyAdapter;
    /** 标签流式适配器 **/
    private LiveCategoryRoomsTagFlowAdapter mTagFlowAdapter;

    /**  **/
    private SparseBooleanArray mTagCheckedBooleanArray = new SparseBooleanArray();

    /** 标签名称列表 **/
    private List<String> mTagNameList = new ArrayList<>();

    /** 分区id **/
    private int mAreaCategoryId = -1;
    /** 页数 **/
    private int mCurrentPage = 1;
    /** 排序 **/
    private String mCurrentSort = "hottest";
    /** 标签 **/
    private String mCurrentTag = "全部";

    @Override
    protected int getCurrentMenuItemId() {
        return R.menu.menu_nav;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_live_category_rooms;
    }

    @Override
    protected void setupViews() {
        ButterKnife.bind(this);
        showBackBtn();

        // 初始化标签列表
        mTagRecyAdapter = new LiveCategoryRoomsTagRecyAdapter(mTagNameList);
        mTagRecyView.setAdapter(mTagRecyAdapter);
        mTagRecyView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int pos) {
                doClickTagTogether(pos);
            }
        });
        // 初始化直播间列表
        initRoomsRecyAdapter();
        // 初始化刷新控件
        mRefreshSRLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 重置为1
                mCurrentPage = 1;
                mPresenter.refreshCategoryRoomsList(mAreaCategoryId, mCurrentPage, mCurrentSort,
                        mCurrentTag);
            }
        });
        // 初始化标签下拉按钮
        mTagOpenImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTagContentLayout2.setVisibility(View.VISIBLE);
            }
        });
        // 初始化第二层标签布局
        mTagContentLayout2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    mTagContentLayout2.setVisibility(View.INVISIBLE);
                }
                return true;
            }
        });
        // 初始化排序按钮
        mSortGroup.check(R.id.rbtn_live_category_rooms_hottest);
        mSortGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rbtn_live_category_rooms_hottest:
                        mCurrentSort = "hottest";
                        break;
                    case R.id.rbtn_live_category_rooms_latest:
                        mCurrentSort = "latest";
                        break;
                }
                doInitCategoryRoomsList();
                mTagContentLayout2.setVisibility(View.INVISIBLE);
            }
        });
    }

    @Override
    protected void initData() {
        mPresenter = new LiveCategoryRoomsPresenter(this);
        // 初始化适配器的数据, 默认选中第一个
        mTagNameList.add("全部");
        mTagCheckedBooleanArray = new SparseBooleanArray();
        mTagCheckedBooleanArray.put(0, true);
        mTagRecyAdapter.setCheckedBooleanArray(mTagCheckedBooleanArray);

        mAreaCategoryId = getIntent().getIntExtra(EXTRA_AREA_CATEGORY_ID, -1);
        if (mAreaCategoryId != -1) {
            mPresenter.initCategoryRoomsTag();
            doInitCategoryRoomsList();
        } else {
            toastHandler("缺少id");
        }

        String title = getIntent().getStringExtra(EXTRA_TITLE);
        if (title != null && !title.isEmpty()) {
            setTitle(title);
        }
    }

    @Override
    public void showCategoryRoomsTag(SparseArray<List<String>> tagSparseArr) {
        List<String> tagNameList = tagSparseArr.get(mAreaCategoryId);
        if (tagNameList != null) {
            mTagNameList.addAll(tagNameList);
            mTagRecyAdapter.notifyDataSetChanged();

            // 设置流式标签的数据以及监听器
            mTagFlowAdapter = new LiveCategoryRoomsTagFlowAdapter(getBaseContext(), mTagNameList);
            mTagFlowAdapter.setOnTagClickListener(new LiveCategoryRoomsTagFlowAdapter
                    .OnTagClickListener() {
                @Override
                public void onTagClick(View view, int position) {
                    doClickTagTogether(position);
                    mTagContentLayout2.setVisibility(View.INVISIBLE);
                }
            });
            mTagTFLayout.setAdapter(mTagFlowAdapter);
            mTagFlowAdapter.setSelectedTag(0);
        }
    }

    @Override
    public void showCategoryRoomsList(List<LiveItemBean> roomsList) {
        mRoomsRecyAdapter.setNewData(roomsList);
    }

    @Override
    public void showMoreCategoryRoomsList(final List<LiveItemBean> moreRoomsList) {
        if (moreRoomsList.size() != 0) {
            mRoomsRecyAdapter.addData(moreRoomsList);
            mRoomsRecyAdapter.loadMoreComplete();
            // 页数加一
            mCurrentPage += 1;
        } else {
            mRoomsRecyAdapter.loadMoreEnd();
            mRoomsRecyAdapter.setEnableLoadMore(false);
        }
    }

    @Override
    public void clearRoomsList() {
        if (mRoomsRecyAdapter != null) {
            mRoomsRecyAdapter.setNewData(new ArrayList<LiveItemBean>());
        }
    }

    @Override
    public boolean isConnectNetwork() {
        return NetworkCheckUtil.isNetworkConnected(getBaseContext());
    }

    @Override
    public int getConnectType() {
        return NetworkCheckUtil.getConnectedType(getBaseContext());
    }

    @Override
    public void showLoading() {
        mRefreshSRLayout.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        mRefreshSRLayout.setRefreshing(false);
    }

    @Override
    public void showEmptyView() {
    }

    @Override
    public void showMessage(String message) {
        toastHandler(message);
    }

    /**
     * 初始化直播间列表
     */
    private void initRoomsRecyAdapter() {
        mRoomsRecyAdapter = new LiveCategoryRoomsContentRecyAdapter(new ArrayList<LiveItemBean>());
        mRoomsRecyAdapter.openLoadAnimation();
        mRoomsRecyAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mPresenter.getMoreCategoryRoomsList(mAreaCategoryId, mCurrentPage + 1,
                        mCurrentSort, mCurrentTag);
            }
        });
        mRoomsRecyAdapter.setOnRippleClickListener(new LiveCategoryRoomsContentRecyAdapter
                .onRippleClickListener() {

            @Override
            public void onRippleClick(RippleView rippleView, int position) {
                goActivity(MainActivity.class);
            }
        });
        mRoomsRecvView.setAdapter(mRoomsRecyAdapter);
    }

    /**
     * 两种布局标签共同设置
     *
     * @param pos 点击位置
     */
    private void doClickTagTogether(int pos) {
        // 选中流式标签
        mTagFlowAdapter.setSelectedTag(pos);
        // 清空并设置当前点击的标签
        mTagCheckedBooleanArray.clear();
        mTagCheckedBooleanArray.put(pos, true);
        mTagRecyAdapter.setCheckedBooleanArray(mTagCheckedBooleanArray);
        // 滑动到当前选中的标签
        RecyclerView.ViewHolder orderView = mTagRecyView.findViewHolderForLayoutPosition(pos);
        if (orderView != null) {
            mTagRecyView.smoothScrollBy(mTagRecyView.getLayoutManager().getDecoratedLeft
                    (orderView.itemView), 0);
        } else {
            mTagRecyView.smoothScrollToPosition(pos);
        }

        // 发送请求
        mCurrentTag = mTagNameList.get(pos);
        // 重置为1
        mCurrentPage = 1;
        doInitCategoryRoomsList();
    }

    /**
     * 做初始化获取列表
     */
    private void doInitCategoryRoomsList() {
        mPresenter.initCategoryRoomsList(mAreaCategoryId, mCurrentPage, mCurrentSort,
                mCurrentTag);
    }

}
